package com.gsafety.wellsfort.service.organization.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.common.util.StringUtil;
import com.gsafety.wellsfort.dao.course.CourseDAO;
import com.gsafety.wellsfort.dao.course.CourseRangeDAO;
import com.gsafety.wellsfort.dao.course.ExamPublishRangeDAO;
import com.gsafety.wellsfort.dao.course.WorkPublishRangeDAO;
import com.gsafety.wellsfort.dao.organization.ClassDAO;
import com.gsafety.wellsfort.dao.organization.SchoolDAO;
import com.gsafety.wellsfort.domain.dto.ids.OrganizationDto;
import com.gsafety.wellsfort.domain.dto.school.SchoolDTO;
import com.gsafety.wellsfort.domain.model.course.*;
import com.gsafety.wellsfort.domain.model.organization.Class;
import com.gsafety.wellsfort.domain.model.organization.School;
import com.gsafety.wellsfort.domain.model.security.Admin;
import com.gsafety.wellsfort.domain.vo.ClassTreeVO;
import com.gsafety.wellsfort.domain.vo.PublishRangeTreeVO;
import com.gsafety.wellsfort.domain.vo.SchoolResultVO;
import com.gsafety.wellsfort.domain.vo.SchoolTreeVO;
import com.gsafety.wellsfort.service.common.CityService;
import com.gsafety.wellsfort.service.organization.ISchoolService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: wuming
 * @Date: 2020/5/1 下午3:44
 * @Description
 */
@Slf4j
@Service
public class SchoolServiceImpl implements ISchoolService {

    @Autowired
    SchoolDAO schoolDAO;

    @Autowired
    private ClassDAO classDAO;

    @Autowired
    private CourseRangeDAO courseRangeDAO;

    @Autowired
    private ExamPublishRangeDAO examPublishRangeDAO;

    @Autowired
    private WorkPublishRangeDAO workPublishRangeDAO;

    @Autowired
    private CityService cityService;

    @Autowired
    private CourseDAO courseDAO;


    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public ApiResponse getSchoolDetail(Integer id) {
        School school = schoolDAO.selectByPrimaryKey(id);
        return ApiResponse.success(school);
    }

    /**
     * 获取学校列表
     *
     * @return
     */
    @Override
    public ApiResponse getAll(SchoolDTO schoolDTO) {
        Admin admin = LoginContextUtil.getAdmin();
        if (admin == null) {
            return ApiResponse.error(ResultCode.USER_NOT_HAS_AUTHORITY);
        }
        if (admin.getSchoolId() != 1) {
            //非平台管理员,只能查看自己学校下的数据
            schoolDTO.setSchoolId(admin.getSchoolId());
        }
        Page page = PageHelper.startPage(schoolDTO.getPageNo(), schoolDTO.getPageSize());
        List<School> schoolList = schoolDAO.selectByParam(schoolDTO);
        PageInfo pageInfo = new PageInfo(page);
        if (CollectionUtils.isEmpty(schoolList)) {
            return ApiResponse.success();
        }
        pageInfo.setList(schoolList);
        log.info("学校列表响应参数={}", schoolList);
        return ApiResponse.success(schoolList, (int) pageInfo.getTotal());
    }

    /**
     * 增加学校
     *
     * @param school
     * @return
     */
    @Override
    public ApiResponse addSchool(School school) {
        Date date = new Date();
        school.setCreator(LoginContextUtil.getUserName());
        school.setOperator(LoginContextUtil.getUserName());
        school.setCreated(date);
        school.setModified(date);
        if (schoolDAO.insert(school) == 1) {
            return ApiResponse.success();
        }
        return ApiResponse.error();
    }

    @Override
    public ApiResponse batchAddSchool(List<School> list) {
        if (list != null && list.size() > 0) {
            for (School school : list) {
                if (StringUtils.isEmpty(school.getName())) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "学校名称不能为空!");
                }
                Integer provinceId = cityService.getCityCodeByName(school.getProvinceName());
                if (StringUtils.isEmpty(school.getProvinceName()) || provinceId == null) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "省份名称输入不合法!");
                }
                Integer cityId = cityService.getCityCodeByName(school.getCityName());
                if (StringUtils.isEmpty(school.getCityName()) || cityId == null) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "城市名称输入不合法!");
                }
                Integer countyId = cityService.getCityCodeByName(school.getCountyName());
                if (StringUtils.isEmpty(school.getCountyName()) || countyId == null) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "县名称输入不合法!");
                }
                if (StringUtils.isEmpty(school.getAddress())) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "详细地址不能为空!");
                }
                if (StringUtils.isEmpty(school.getManagerName())) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "负责人不能为空!");
                }
                if (StringUtils.isEmpty(school.getManagerPhone())) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "负责人联系方式不能为空!");
                }
                if (StringUtils.isEmpty(school.getMasterName())) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "校长姓名不能为空!");
                }
                if (school.getStudentNumber() == null) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "学生数量不能为空!");
                }
                if (school.getTeacherNumber() == null) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "教职工数量不能为空!");
                }
                if (school.getStatus() == null || (school.getStatus().intValue() != 0 && school.getStatus().intValue() != 1)) {
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "状态输入不合法!");
                }
                if(school.getExt1()==null && !isNumber(school.getExt1())){
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "所在地经度输入不合法!");
                }
                if(school.getExt2()==null && !isNumber(school.getExt2())){
                    return ApiResponse.error(ResultCode.ERROR.getCode(), "所在地纬度输入不合法!");
                }
                school.setProvinceId(provinceId);
                school.setCityId(cityId);
                school.setCountyId(countyId);
                this.addSchool(school);
            }
        }
        return ApiResponse.success();
    }

    private boolean isNumber(String str){
        try {
            Double.parseDouble(str);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    @Override
    public ApiResponse list(SchoolDTO schoolDTO) {
        List<SchoolResultVO> resultVOList = new ArrayList<>();
        List<School> list = schoolDAO.list(schoolDTO);
        SchoolResultVO resultVO = null;
        if (list != null && list.size() > 0) {
            for (School school : list) {
                resultVO = new SchoolResultVO();
                BeanUtils.copyProperties(school, resultVO);
                resultVOList.add(resultVO);
            }
        }
        return ApiResponse.success(resultVOList);
    }

    @Override
    public ApiResponse<List<School>> list() {
        List<School> list = schoolDAO.list(new SchoolDTO());
        return ApiResponse.success(list);
    }

    @Override
    public School get(Integer id) {
        return schoolDAO.selectByPrimaryKey(id);
    }

    @Override
    public ApiResponse update(School school) {
        if (school.getId() == null) {
            return ApiResponse.error(ResultCode.INVALID_PARAM);
        }
        school.setModified(new Date());
        Integer update = schoolDAO.updateByPrimaryKeySelective(school);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse<PublishRangeTreeVO> getOrganization(OrganizationDto organizationDto) {
        PublishRangeTreeVO publishRangeTreeVO = new PublishRangeTreeVO();
        publishRangeTreeVO.setSelectAll(false);
        List<SchoolTreeVO> treeList = new ArrayList<>();
        Admin admin = LoginContextUtil.getAdmin();
        if (admin == null) {
            return ApiResponse.error(ResultCode.NOT_AUTHORIZED);
        }
        if (organizationDto.getType() == null) {
            return ApiResponse.error(ResultCode.INVALID_PARAM);
        }
        List<School> schoolList = new ArrayList<>();
        if (admin.getSchoolId() == 1) {
            //管理员获取所有学校组织机构
            schoolList = schoolDAO.getAllList();
        } else {
            //学校管理员获取当前学校组织机构
            School school = schoolDAO.selectByPrimaryKey(admin.getSchoolId());
            schoolList.add(school);
        }
        Set<Integer> checkedSchoolIdList = new HashSet<>();
        Set<Integer> checkedClassIdList = new HashSet<>();
        if (organizationDto.getId() != null) {
            if (organizationDto.getType() == 1) {
                Course course = courseDAO.selectByPrimaryKey(organizationDto.getId());
                if (course != null && course.getIsPlatform() == 1) {
                    publishRangeTreeVO.setSelectAll(true);
                } else {
                    List<CourseRange> courseRangeList = courseRangeDAO.selectByCourseId(organizationDto.getId());
                    if (courseRangeList != null && courseRangeList.size() > 0) {
                        for (CourseRange courseRange : courseRangeList) {
                            checkedSchoolIdList.add(courseRange.getSchoolId());
                            checkedClassIdList.add(courseRange.getClassId());
                        }
                    }
                }
            } else if (organizationDto.getType() == 2) {
                List<ExamPublishRange> examPublishRangeList = examPublishRangeDAO.selectByExamPublishId(organizationDto.getId());
                if (examPublishRangeList != null && examPublishRangeList.size() > 0) {
                    for (ExamPublishRange examPublishRange : examPublishRangeList) {
                        checkedSchoolIdList.add(examPublishRange.getSchoolId());
                        checkedClassIdList.add(examPublishRange.getClassId());
                    }
                }
            } else if (organizationDto.getType() == 3) {
                List<WorkPublishRange> workPublishRangeList = workPublishRangeDAO.selectByWorkPublishId(organizationDto.getId());
                if (workPublishRangeList != null && workPublishRangeList.size() > 0) {
                    for (WorkPublishRange workPublishRange : workPublishRangeList) {
                        checkedSchoolIdList.add(workPublishRange.getSchoolId());
                        checkedClassIdList.add(workPublishRange.getClassId());
                    }
                }
            }
        }
        SchoolTreeVO tree = null;
        if (schoolList != null && schoolList.size() > 0) {
            for (School school : schoolList) {
                tree = new SchoolTreeVO(school.getId(), school.getName(), checkedSchoolIdList.contains(school.getId()));
                List<Class> classList = classDAO.selectBySchoolId(school.getId());
                if (classList != null && classList.size() > 0) {
                    for (Class cls : classList) {
                        ClassTreeVO child = new ClassTreeVO(cls.getId(), cls.getName(), checkedClassIdList.contains(cls.getId()));
                        tree.addChildren(child);
                    }
                }
                treeList.add(tree);
            }
        }
        publishRangeTreeVO.setList(treeList);
        return ApiResponse.success(publishRangeTreeVO);
    }

    @Override
    public ApiResponse<PublishRangeTreeVO> getDefaultOrganization() {
        PublishRangeTreeVO publishRangeTreeVO = new PublishRangeTreeVO();
        publishRangeTreeVO.setSelectAll(false);
        List<SchoolTreeVO> treeList = new ArrayList<>();
        Admin admin = LoginContextUtil.getAdmin();
        if (admin == null) {
            return ApiResponse.error(ResultCode.NOT_AUTHORIZED);
        }

        List<School> schoolList = new ArrayList<>();
        if (admin.getSchoolId() == 1) {
            //管理员获取所有学校组织机构
            schoolList = schoolDAO.getAllList();
        } else {
            //学校管理员获取当前学校组织机构
            School school = schoolDAO.selectByPrimaryKey(admin.getSchoolId());
            schoolList.add(school);
        }
        SchoolTreeVO tree = null;
        if (schoolList != null && schoolList.size() > 0) {
            for (School school : schoolList) {
                tree = new SchoolTreeVO(school.getId(), school.getName(), false);
                List<Class> classList = classDAO.selectBySchoolId(school.getId());
                if (classList != null && classList.size() > 0) {
                    for (Class cls : classList) {
                        ClassTreeVO child = new ClassTreeVO(cls.getId(), cls.getName(), false);
                        tree.addChildren(child);
                    }
                }
                treeList.add(tree);
            }
        }
        publishRangeTreeVO.setList(treeList);
        return ApiResponse.success(publishRangeTreeVO);
    }

    @Override
    public Integer count() {
        return schoolDAO.count();
    }
}
